﻿/*******************************************************
* Copyright (c) 2018-2088, By XuXiang all rights reserved.
*
* FileName: ModuleConfig.h
* Summary: 模块配置的基类。
*
* Author: XuXiang
* Date: 2018-12-06 14:30
*******************************************************/

#ifndef __ModuleConfig_h__
#define __ModuleConfig_h__

#include "../Macro.h"
#include "CSVLoader.h"
#include "ConfigWrap.h"
#include <map>
#include <vector>
using namespace std;

namespace Competition
{
#define CONFIG_MAP(cfg) typedef map<int, cfg*> cfg##Map

	class ModuleConfig
	{
	public:
		ModuleConfig();
		virtual ~ModuleConfig();

		//初始化
		void Init();

		//销毁
		void Release();

		//获取名称
		virtual const char* GetName()const = 0;

		//获取是否已经初始化过了
		inline bool IsInit()const { return m_Init; }

		//获取实例
		template<class T>
		static T* GetInstance();

		//加载配置
		//cfg:保存配置的集合
		//file:Lua配置名称
		template<class T>
		static void LoadConfig(map<int, T*>& cfgs, const string& name);

	protected:

		//初始化
		virtual void OnInit() = 0;

		//销毁
		virtual void OnRelease() = 0;

	private:

		//是否已经初始化了
		bool m_Init;
	};

	template<class T>
	T* ModuleConfig::GetInstance()
	{
		static T t;
		return &t;
	}

	template<class T>
	void ModuleConfig::LoadConfig(map<int, T*>& cfgs, const string& name)
	{
		CSVLoader loader;
		char file[255];
		::sprintf(file, "Configs/%sConfig.csv", name.c_str());
		loader.Init(file);
		cfgs.clear();
		while (loader.ReadNextRecord())
		{
			ConfigWrap* wrap = ConfigWrap::OnNew<T>();
			wrap->Read(&loader);
			wrap->OnParse();

			T* t = dynamic_cast<T*>(wrap);
			cfgs.insert(make_pair(wrap->GetUniqueKey(), t));
		}
	}
}

#endif
